<template>
  <div class="page-leveladd">
    <pk-dialog :title="title" @confirm="confirm" @onClose="onClose" width="500px">
      <div class="mt-12 mb-12">
        <pk-form :formConfig="formConfig" labelPosition="top" ref="myForm"></pk-form>
      </div>
    </pk-dialog>
  </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, onMounted } from 'vue'
import pkDialog from '@/components/pkui/pk-dialog/pk-dialog.vue'
import pkForm from '@/components/pkui/pk-form/pk-form.vue'
import { accountCreate, accountUpdate } from '@/api/api'
import { AES_Encrypt } from '@/utils/3des'
const emit = defineEmits(['confirm', 'onClose'])
const props = defineProps({
  curData: {
    type: Object,
    default: () => {}
  }
})
const title = ref('添加账号')
const myForm = ref(null)
const formConfig = ref([ 
  // {
  //   label: '账号名',
  //   type: 'input',
  //   prop: 'account'
  // },
  {
    label: '手机号码',
    type: 'input',
    prop: 'phone'
  },
  {
    label: '密码',
    type: 'input',
    prop: 'password',
    showPassword: true
  },
  {
    label: '姓名',
    type: 'input',
    prop: 'realname'
  }, 
  // {
  //   label: '邮箱',
  //   type: 'input',
  //   prop: 'email'
  // }, 
  {
    label: '状态',
    type: 'radio',
    prop: 'locked',
    options: [
      {
        label: '正常',
        value: 0
      },
      {
        label: '禁用',
        value: 1
      }
    ]
  },  
])


const onClose = () => {
  emit('onClose')
}

const postAdd = (data) => {
  accountCreate({
    ...data,
    username: data.phone,
    password: AES_Encrypt(data.password),
    locked: 0
  }).then(res => {
    emit('confirm')
  })
}

const postEdit = (data) => {
  let params = {
    ...data,
    id: props.curData.id,
    locked: 0
  }
  delete params.password
  accountUpdate(params).then(res => {
    emit('confirm')
  })
}

const confirm = () => {
  myForm.value.submitForm().then(res => {
    if (props.curData?.id) {
      postEdit(res)
    } else {
      postAdd(res)
    }
  })
}

const initStart = () => {
  if (props.curData?.id) {
    title.value = '编辑账号'
    myForm.value.setFormProp('phone', props.curData.phone)
    myForm.value.setFormProp('realname', props.curData.realname)
    myForm.value.setFormProp('locked', props.curData.locked)
    formConfig.value[1].show = false
  } else {
    title.value = '添加账号'
  }
}
onMounted(() => {
  setTimeout(() => {
    initStart()
  }, 100)
})

</script>

<style lang="scss" scoped>

</style>